import axios from 'axios'

function getLoginInfo() {
    return JSON.parse(localStorage.getItem('userInfo'))
}

let env = process.env.NODE_ENV
//const ajaxUrl = env === 'development' ? '/api/' : 'http://localhost:8099/xxpt/web/'
//const ajaxUrl = env === 'development' ? '/api/' : 'http://115.29.226.80:8099/xxpt/web/'
//const ajaxUrl = env === 'development' ? '/api/' : 'http://112.124.28.76:8099/xxpt/web/'
//const ajaxUrl = env === 'development' ? '/api/' : 'http://192.168.102.248:8099/xxpt/web/'
const ajaxUrl = env === 'development' ? '/api/' : 'http://25.20.199.49:8099/xxpt/web/'
let utils = {}
utils.baseURL = ajaxUrl

utils.api = {
    // 课程相关
    curriculum: {
        list: 'curriculum/list'
    },
    examInfo: {
        getExamRemainTime: 'examination/getExamRemainTime',
        examSubmit: 'examination/ExamSubmit',
        userCenter: 'examination/UserCenter'
    },
    policyInfo: {
        policyList: 'policyAnalysis/list',
        policyNewsList: 'policy/list',
        themeTypeList: 'policy/ThemeTypeList',
        policyNewsDetail: 'policy/detail',
        policyDetail: 'policyAnalysis/detail',
        registerDownnum: 'policy/registerDownnum'//记录下载数
    },
    politicalInfo: {
        newsList: 'notice/list',
        routineList: 'notice/RoutineList',
        newsDetail: 'notice/detail'
    },
    sideRank: {
        student: 'examination/StudentsRanking',
        dept: 'examination/DeptRanking'
    },
    politicalWorkPlan: {
        myList: 'plan/myList',
        groupList: 'plan/groupList',
        leaderList: 'plan/leaderList',
        groupNameList: 'plan/groupNameList',
        leaderApproval: 'plan/leaderApproval'
    },

    // 在线咨询
    websocketURL: process.env.BASE_URL,
    websocketURL: {

        // websocket连接
        wsUrl: process.env.BASE_URL,

        // 获取用户sid
        view: 'psychologicalCounseling/view',

        // 在线聊天 {userId}/{sid}
        psyWebsocket: 'PsyWebsocket',




    },

    psychological: {
        dutyList: 'therapist/dutyList',
        consultant: 'therapist/list',
    },
}

utils.getQueryString = function (name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
    var r = window.location.href.substr(window.location.href.lastIndexOf('?') + 1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}

axios.defaults.headers.common['token'] = ''
axios.defaults.baseURL = ajaxUrl
utils.ajax = axios
utils.axios = axios

utils.replaceFirstUpperCase = str => {
    return str.replace(/\b(\w)|\s(\w)/g, function (m) {
        return m.toUpperCase()
    })
}

// author: meizz
// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date()).Format('yyyy-MM-dd hh:mm:ss.S') ==> 2006-07-02 08:09:04.423
// (new Date()).Format('yyyy-M-d h:m:s.S')      ==> 2006-7-2 8:9:4.18
// eslint-disable-next-line
Date.prototype.Format = function (fmt) {
    let o = {
        'M+': this.getMonth() + 1, // 月份
        'd+': this.getDate(), // 日
        'h+': this.getHours(), // 小时
        'm+': this.getMinutes(), // 分
        's+': this.getSeconds(), // 秒
        'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
        S: this.getMilliseconds() // 毫秒
    }
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(
            RegExp.$1,
            (this.getFullYear() + '').substr(4 - RegExp.$1.length)
        )
    }
    for (let k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
            fmt = fmt.replace(
                RegExp.$1,
                RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
            )
        }
    }
    return fmt
}

utils.getCountdownDay = function (val) {
    if (val && val.indexOf('0001-01-01') === -1) {
        return Math.ceil((new Date(val.replace(/-/g, '/')).getTime() - new Date().getTime()) / (24 * 60 * 60 * 1000));
    } else {
        return 0;
    }
}

/**
 * 简单通用post提交
 * @param {String} url
 * @param {Json} params 参数
 * @param {Function} callback 回调函数
 * @param {Boolean} isAutoFail 自动处理失败
 */
utils.post = (url, params, callback, isAutoFail = true) => {
    if (process.env.NODE_ENV !== 'production') {
        console.log('post->url[' + url + '], post->params[' + JSON.stringify(params) + ']')
    }
    utils.axios.defaults.headers.common['token'] = localStorage.getItem('token')
    utils.ajax.post(url, params).then(res => {
        var loginInfo = getLoginInfo()
        // 处理 401 登录失效的情况
        if (res.data.code === 500 && ~res.data.msg.indexOf('401')) {
            if (loginInfo && loginInfo.name) {
                if (!window.$showMessage) {
                    window.Vue.prototype.$message({
                        message: '您尚未登录',
                        type: 'warning'
                    });
                    window.$showMessage = true
                }
            }
            return
        }

        res.data.success = res.data.code === 1
        if (callback) {
            callback(res.data)
            if (isAutoFail) {
                if (!res.data.success) {
                    if ((loginInfo && loginInfo.name) || url.indexOf('/login') > -1) {
                        window.Vue.prototype.$message.error(res.data.msg)
                    }
                }
            }
        }
        if (url !== utils.api.examInfo.userCenter) {
            utils.common.getUserExtras()
        }
    }).catch(error => {
        console.error(error);
        // if (!isAutoFail && callback) {
        //     // eslint-disable-next-line
        //     callback({ success: false, message: error.message })
        // } else {
        //     var loginInfo = JSON.parse(localStorage.getItem('userInfo'))
        //     if (loginInfo && loginInfo.name) {
        //         window.Vue.prototype.$message.error(error.message.toLowerCase() === 'network error' ? utils.message.networkError : error.message)
        //     }
        // }
    })
}

utils.get = (url, callback) => {
    utils.axios.defaults.headers.common['token'] = localStorage.getItem('token')
    utils.ajax.get(url).then(res => {
        var loginInfo = getLoginInfo()
        // 处理 401 登录失效的情况
        if (res.data.code === 500 && ~res.data.msg.indexOf('401')) {
            // TODO
            window.Vue.prototype.$message({
                message: '您尚未登录',
                type: 'warning'
            });
            return
        }

        res.data.success = res.data.code === 1
        if (callback) {
            callback(res.data)
            if (!res.data.success) {
                if ((loginInfo && loginInfo.name) || url.indexOf('/login') > -1) {
                    window.Vue.prototype.$message.error(res.data.msg)
                }
            }
        }
        if (url !== utils.api.examInfo.userCenter) {
            utils.common.getUserExtras()
        }
    }).catch(error => {
        console.error(error);
        // var loginInfo = JSON.parse(localStorage.getItem('userInfo'))
        // if (loginInfo && loginInfo.name) {
        //     window.Vue.prototype.$message.error(error.message.toLowerCase() === 'network error' ? utils.message.networkError : error.message)
        // }
        // if (callback) {
        //     // eslint-disable-next-line
        //     callback({ success: false, isNetworkError: error.message.toLowerCase() === 'network error' })
        // }
    })
}

utils.message = {
    success: '操作成功!',
    fail: '操作失败!',
    delete: '删除失败,请重新提交!',
    update: '更新失败,请重新提交!',
    confirmDelete: '是否确定要删除，删除后数据无法恢复!',
    nullData: '没有选中的数据',
    noneModifyData: '未找到修改的数据',
    unique: '{0}已经存在',
    uniqueDefault: '唯一验证失败,此数据已存在',
    editOne: '当前只能编辑一条数据',
    required: '请输入{0}',
    networkError: '远程服务器无响应',
    validNumber: '{0}必需是数字'
}

utils.setItem = function (key, value) {
    localStorage.setItem(key, JSON.stringify(value))
}

utils.getItem = function (key) {
    return JSON.parse(localStorage.getItem(key))
}

utils.countdown = function (val) {
    var seconds = val;// 秒
    var minutes = 0;// 分
    var hour = 0;// 小时

    if (seconds > 60) {
        minutes = Math.floor(seconds / 60)
        seconds = Math.floor(seconds % 60)
        if (minutes >= 60) {
            hour = Math.floor(minutes / 60)
            minutes = Math.floor(minutes % 60)
        }
        // 特殊处理60秒，60分
        if (seconds === 0 && minutes > 0) {
            minutes--
            seconds = 59
            hour = hour - 1 > 0 ? hour - 1 : 0
        }
    }
    var result = hour.toString().padStart(2, '0') + ':' + minutes.toString().padStart(2, '0') + ':' + seconds.toString().padStart(2, '0');
    return result;
}

utils.convertTime = function (val) {
    var seconds = val;// 秒
    var minutes = 0;// 分
    var hour = 0;// 小时

    if (seconds > 60) {
        minutes = Math.floor(seconds / 60)
        seconds = Math.floor(seconds % 60)
        if (minutes >= 60) {
            hour = Math.floor(minutes / 60)
            minutes = Math.floor(minutes % 60)
        }
    }
    var result = hour.toString().padStart(2, '0') + ':' + minutes.toString().padStart(2, '0') + ':' + seconds.toString().padStart(2, '0');
    return result;
}

utils.stopRefresh = function () {
    var UnloadConfirm = {}
    UnloadConfirm.MSG_UNLOAD = '正在考试中，不允许离开'
    UnloadConfirm.set = function (a) {
        window.onbeforeunload = function (b) {
            b = b || window.event
            b.returnValue = a
            return a
        }
    }
    UnloadConfirm.clear = function () {
        window.onbeforeunload = function () { }
    }
    UnloadConfirm.set(UnloadConfirm.MSG_UNLOAD)
}

utils.goTop = function () {
    window.scrollTo(0, 0)
}

utils.checkStartExam = function () {
    return sessionStorage.getItem('startExam') === '1'
}

utils.setStartExam = function (status) {
    sessionStorage.setItem('startExam', status)
}

utils.common = {
    getUserExtras() {
        utils.post(utils.api.examInfo.userCenter, {}, res => {
            if (res.success) {
                var userInfo = {
                    name: res.data.userName,
                    credits: res.data.points,
                    unitRanking: res.data.deptOrder,
                    collegeRanking: res.data.schoolOrder,
                    cumulativeHours: Math.floor(res.data.studyTimeLong / 60),
                    examsCount: res.data.examinationNum,
                    waitWorkCount: res.data.manageOfficeNum,
                    todoCount: res.data.scheduleNum
                }
                window.store.commit('setUserInfo', userInfo)
            }
        })
    }
}
export default utils
